package com.gopay.scheduler.job;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.domain.cps.cbrmb.Tran01734VO;
import com.gopay.common.domain.cps.cbrmb.Tran01734VO.Action;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.order.dao.CommonQueryDAO;
import com.gopay.common.util.DateUtils;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;

/**
 * 跨境人民币调工行大额接口Job
 * CbRmbIcbcToCcbJob.java
 * @author qld
 * @2017年1月19日 上午9:27:34  www.gopay.com.cn Inc.All rights reserved.
 * @2017年4月17日再次修改  
 * @2018年6月6日再次修改
 * 逻辑： 工作日大于5w的拨款时间为9:00-16:30</br>      
 *     小于5w的7*24小时，没有限制
 */
public class CbRmbIcbcToCcbJob extends GopayBaseJob {
    // 日志
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Resource(name = "commonQueryDAO")
    private CommonQueryDAO commonQueryDAO;

    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;

    //工行大额系统的金额分界点
    private final static int MAX_AMT=50000;

    @Override
    public void doJobInternal() {
        logger.error("跨境的CbRmbIcbcToCcbJob------start------");

        //调工行的大额接口
        doCbRmbIcbcToCcbOrder();

        logger.error("跨境的CbRmbIcbcToCcbJob------end------");
    }

    /**
     * 01734的订单，付款状态是待确认付款的 汇款的订单还没有发生退款的
     * 原订单是01723,01724,01725的增加了资料审核（CB_RMB_APPROVE）审核通过后才可以拨款
     */
    private void doCbRmbIcbcToCcbOrder(){
        StringBuilder sb = new StringBuilder();

        sb.append(" select m.gopay_order_id,m.gopay_int_txn_cd,m.mer_txn_amt from cps_gen_main_order m  ");
        sb.append(" left join cps_gen_pay_order p on p.gopay_order_id=m.gopay_order_id ");
        sb.append(" left join cps_gen_main_order orgOrder on m.relevance_gopay_order_id = orgOrder.gopay_order_id ");
        sb.append(" left join CB_RMB_APPROVE apv on m.relevance_gopay_order_id = apv.gopay_order_id ");
        sb.append(" left join CB_RMB_TRAN_ASSIST_DTL crtad on m.relevance_gopay_order_id = crtad.gopay_order_id ");
        sb.append("  where 1=1 ");
        sb.append("  and p.PAY_STAT='01' ");
        sb.append("  and m.txn_sta_cd="+TxnStaCode.TXN_STA_CD_30000.value);
        sb.append("  and m.gopay_int_txn_cd in ('01734') ");
        sb.append("  and ((orgOrder.gopay_int_txn_cd not in ('01723','01724','01725')) or (apv.approve_type='001' and apv.audit_result='1' and crtad.is_corp_name='Y'))");
        sb.append("  and not exists(select 1 from cps_gen_main_order t,cb_rmb_force_refund_record f ");
        sb.append("  where m.relevance_gopay_order_id=t.gopay_order_id  and t.gopay_order_id=f.gopay_order_id and f.REFUND_STATUS!='20003')");

        Map<String, Object> map = new HashMap<String, Object>();

        Date now=new Date();
        Date date1630 = new Date(now.getYear(), now.getMonth(), now.getDate(), 16, 30);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);
        String gopayOrderId,intTxnCd;
        Object paramVo;
        CPSResponse response;
        if (rsList != null && rsList.size() > 0) {
            logger.error("doCbRmbIcbcToCcbOrder--rsList.size="+rsList.size());
            
            for (Object[] arr : rsList) {
                gopayOrderId=(String) arr[0];
                intTxnCd=(String) arr[1];
               
                //获取到单笔的拨款金额
                BigDecimal amt=new BigDecimal(String.valueOf(arr[2]));
                logger.info("单笔订单号:"+gopayOrderId+"的金额是:"+amt);
                //如果金额大于5w且时间不在9:00-16:30 不调大额拨款接口
                //金额大于5w而且是节假日也不拨款
                if(amt.compareTo(new BigDecimal(MAX_AMT))==1&&isHoliday(now)){
                    logger.info("现在时间是:"+now+"金额是:"+amt+",是节假日,所以不走大额接口");
                }
                else if(amt.compareTo(new BigDecimal(MAX_AMT))==1&&(now.getHours()<9||now.after(date1630))){
                    logger.info("现在时间是:"+now+"金额是:"+amt+"所以不走大额接口");
                }
                else{
                	// 封装cps请求参数vo
                    paramVo = buildCallCbrCpsParam(gopayOrderId, intTxnCd);

                    try {
                        logger.error("doCbRmbIcbcToCcbOrder callCps-------gopayOrderId="+gopayOrderId+",intTxnCd="+intTxnCd);
                        // 调用cbrcps
                        response=callCPSHelper.callCbRmbByVOTicket(paramVo);
                        if (!ProcCodeConstants.PROC_CODE_100S1000.equals(response.getRespCode())) {
                            logger.error("------doCbRmbIcbcToCcbOrder 调用cps返回异常  response="+response.getRespCode());
                        }else{
                            logger.error("------doCbRmbIcbcToCcbOrder 调用cps返回成功受理  response="+response.getRespCode());
                        }
    
                    } catch (Exception e) {
                        // 吃掉所有异常
                        logger.error("doCbRmbIcbcToCcbOrder callByVOTicket Error", e);
                    }
                }
            }
        }
    }

    private Object buildCallCbrCpsParam(String gopayOrderId,String intTxnCd) {
		Object obj = null;
		Tran01734VO paramVo = new Tran01734VO();
		paramVo.setGopayOrderId(gopayOrderId);
		paramVo.setAction(Action.APPLY);
		obj = paramVo;

		return obj;
    }

    /**
     * 是否为节假日,暂时就用节假日表01类型
     * @return
     */
    public boolean isHoliday(Date date){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        String year = DateUtils.format(calendar.getTime(), "yyyy");
        String month = DateUtils.format(calendar.getTime(), "M");
        String day = DateUtils.format(calendar.getTime(), "d");
        
        StringBuilder sb = new StringBuilder();
        
        sb.append(" select t.year, t.month, t.holidays ");
        sb.append("   from holiday_information t ");
        sb.append("  where 1 = 1       ");
        sb.append("    and ','||t.holidays||',' like :holidays ");
        sb.append("    and t.month=:month ");
        sb.append("    and t.year=:year ");
        sb.append("    and t.holiday_type = '01' ");

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("holidays", "%,"+day+",%");
        map.put("month", month);
        map.put("year", year);

        List<Object[]> rsList = commonQueryDAO.findBySql(sb.toString(), map);

        return rsList != null && rsList.size() > 0;
    }
    
}
